package com.huixin.zhang.common.utils;

import com.huixin.zhang.common.bean.UploadResultBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Slf4j
public class UploadUtils {
    public static UploadResultBean upload(String serverPath, String destFilePath, MultipartFile file) throws IOException {
        String newFileName = FileUtils.getNewFileName(file.getOriginalFilename());
        UploadResultBean result = new UploadResultBean();
        result.setFileSize(file.getSize());
        result.setFileType(file.getContentType());
        result.setCommonsPath(serverPath);
        result.setOldFileName(file.getOriginalFilename());
        result.setNewFileName(newFileName);
        StringBuilder builder = new StringBuilder();
        builder.append(result.getCommonsPath());
        Date now = new Date();
        if(StringUtils.isNotBlank(destFilePath)) {
            if(!destFilePath.startsWith("/")){
                builder.append("/");
            }
        	 builder.append(destFilePath);
             if(!destFilePath.endsWith("/")){
                 builder.append("/");
             }
            builder.append(DateTimeUtils.format(now, "yyyy/MM/dd/"));
            File dirFile = new File(builder.toString());
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }
        } else {
            if(!serverPath.endsWith("/")){
                builder.append("/");
            }
        }
        builder.append(newFileName);
        file.transferTo(new File(builder.toString()));
        log.debug("上传文件：" + builder.toString());
        result.setAbsolutePath(builder.toString());
        result.setRelativePath(result.getAbsolutePath().replace(result.getCommonsPath(), ""));
        result.setUploadTime(now);
        return result;
    }
}
